import { Modal, Table, Button, Input, Toast, Popover } from "@douyinfe/semi-ui";
import {
  IconDelete,
  IconExternalOpen,
  IconSetting,
  IconSourceControl,
} from "@douyinfe/semi-icons";
import { useEffect, useState } from "react";
import { useRequest } from "ahooks";
import {
  findAllDrawData,
  saveDrawData,
  deleteDrawData,
  updateDrawData,
} from "../../../api/request";
import Sharing from "./Sharing";

const Cloud = (props) => {
  const { visible, onTransmit, onCancel } = props;
  const [createVisible, setCreateVisible] = useState(false);
  const [updateVisible, setUpdateVisible] = useState(false);
  const [coundName, setCoundName] = useState("");
  const [updateNameData, setUpdateNameData] = useState();
  const [tableData, setTableData] = useState([]);
  const [modal, contextHolder] = Modal.useModal();
  const [sharingVisible, setSharingVisible] = useState(false);
  const [drawdbDataId, setDrawdbDataId] = useState();

  const { run: findAllDrawDataRun } = useRequest(findAllDrawData, {
    manual: true,
    onSuccess(result) {
      setTableData(result.data.records);
    },
  });

  const { run: deleteDrawDataRun } = useRequest(deleteDrawData, {
    manual: true,
    onSuccess() {
      findAllDrawDataRun();
      Toast.success("删除成功");
    },
  });

  const { run: saveDrawDataRun } = useRequest(saveDrawData, {
    manual: true,
    onSuccess() {
      Toast.success("保存成功");
      findAllDrawDataRun();
      setCreateVisible(false);
      setCoundName(undefined);
    },
  });

  const { run: updateDrawDataRun } = useRequest(updateDrawData, {
    manual: true,
    onSuccess() {
      Toast.success("修改成功");
      findAllDrawDataRun();
      setUpdateVisible(false);
      setCoundName(undefined);
    },
  });

  useEffect(() => {
    if (visible) {
      findAllDrawDataRun();
    }
  }, [visible, findAllDrawDataRun]);

  /** 删除云数据 */
  const removeRecord = (key) => {
    modal.confirm({
      title: "删除",
      content: "确定删除？",
      okText: "删除",
      cancelText: "取消",
      onOk() {
        deleteDrawDataRun(key);
      },
    });
  };

  /** 打开云存储数据 */
  const openDrawDb = (record) => {
    modal.confirm({
      title: "打开",
      content: "打开当前图表会覆盖已有的图表？",
      okText: "确定",
      cancelText: "取消",
      onOk() {
        onTransmit(record);
      },
    });
  };

  const columns = [
    {
      title: "名称",
      dataIndex: "name",
      width: 180,
    },
    {
      title: "日期",
      dataIndex: "createdTime",
    },
    {
      title: "操作",
      width: 160,
      render: (text, record) => (
        <>
          {(!record.isShare ||
            record.drawdbUserId ==
              JSON.parse(localStorage.getItem("userData")).id) && (
            <Popover
              showArrow
              content={<article>删除</article>}
              position={"top"}
            >
              <Button
                icon={<IconDelete />}
                theme="borderless"
                onClick={() => removeRecord(record.id)}
              />
            </Popover>
          )}

          <Popover
            showArrow
            content={<article>修改图表</article>}
            position={"top"}
          >
            <Button
              icon={<IconSetting />}
              theme="borderless"
              onClick={() => {
                setUpdateVisible(true);
                setUpdateNameData(record);
              }}
            />
          </Popover>
          <Popover
            showArrow
            content={<article>打开图表</article>}
            position={"top"}
          >
            <Button
              icon={<IconExternalOpen />}
              theme="borderless"
              onClick={() => openDrawDb(record)}
            />
          </Popover>

          {(!record.isShare ||
            record.drawdbUserId ==
              JSON.parse(localStorage.getItem("userData")).id) && (
            <Popover
              showArrow
              content={<article>共享图表</article>}
              position={"top"}
            >
              <Button
                icon={<IconSourceControl />}
                theme="borderless"
                onClick={() => {
                  setDrawdbDataId(record.id);
                  setSharingVisible(true);
                }}
              />
            </Popover>
          )}
        </>
      ),
    },
  ];

  return (
    <>
      <Modal
        title="云存储"
        visible={visible}
        cancelText="本地开发"
        okText="新建云存储"
        onCancel={onCancel}
        width={600}
        footer={
          <Button type="primary" onClick={() => setCreateVisible(true)}>
            新建云存储
          </Button>
        }
      >
        <div className="max-h-[400px] overflow-auto">
          <Table
            columns={columns}
            dataSource={tableData}
            pagination={false}
            rowKey={(record) => record.id}
          />
        </div>
      </Modal>
      <Modal
        title="新建云存储"
        visible={createVisible}
        cancelText="取消"
        okText="确定"
        onOk={() => {
          if (coundName) {
            const userData = JSON.parse(localStorage.getItem("userData"));
            saveDrawDataRun({ name: coundName, drawdbUserId: userData.id });
          } else {
            Toast.error("名称必填");
          }
        }}
        onCancel={() => setCreateVisible(false)}
      >
        <Input
          placeholder={"请输入名称"}
          onChange={(data) => setCoundName(data)}
          value={coundName}
        />
      </Modal>
      <Modal
        title="修改名称"
        cancelText="取消"
        okText="确定"
        visible={updateVisible}
        onCancel={() => setUpdateVisible(false)}
        onOk={() => {
          if (updateNameData) {
            updateDrawDataRun({ ...updateNameData });
          } else {
            Toast.error("名称必填");
          }
        }}
      >
        <Input
          placeholder={"请输入名称"}
          onChange={(name) => setUpdateNameData((data) => ({ ...data, name }))}
          value={updateNameData?.name}
        />
      </Modal>

      <Sharing
        visible={sharingVisible}
        onCancel={() => setSharingVisible(false)}
        drawdbDataId={drawdbDataId}
      />
      {contextHolder}
    </>
  );
};

export default Cloud;
